#include <stdio.h>
#include <string.h>
#include <regex.h>
#include <stdlib.h>


struct Uart
{
    char *Name;
    char *Speed;
    char *Bit;
    char *Event;
    char *Stop;
};

int readConfig(char *filePath, struct Uart *mp);
char *reStr(char *test_str, char *reg_str);



int main()
{
    struct Uart mmUart = {}; 
    struct Uart *mp;
    mp = &mmUart;
    readConfig("config.ini", mp);
    // printf("main:%s",mp->Name);
    printf("end %s",mp->Name);
    printf("end %s",mp->Speed);
    printf("end %s",mp->Bit);
    printf("end %s",mp->Event);
    printf("end %s",mp->Stop);
    return 0;
}
// 读取配置文件
int readConfig(char *filePath, struct Uart *mmp)
{
    char buf[1024];
    FILE *fp;

    if ((fp = fopen(filePath, "r")) == NULL)
    {
        perror("fail to fopen");
        return -1;
    }

    char *myresult = NULL;
    char *myKey = NULL; 
    char *reg_str = "= (.*)";
    char *first_str = "(.*) =";
    while (fgets(buf, 1024, fp) != NULL)
    {
        if (strchr(buf,'=') == NULL)
        {
            continue;
        }
        myKey = reStr(buf, first_str);
        myresult = reStr(buf, reg_str);
        printf("键：%s\n",myKey);
        printf("值：%s\n",myresult);
        // strncmp 完全相等返回0
        if (strncmp(myKey,"Name",4) == 0)
            mmp->Name = myresult;
            // printf("==Name");
        if (strncmp(myKey,"Speed",5) == 0)
            mmp->Speed = myresult;
            // printf("==Speed");
        if (strncmp(myKey,"Bit",3) == 0)
            mmp->Bit = myresult;
            // printf("==Bit");
        if (strncmp(myKey,"Event",5) == 0)
            mmp->Event = myresult;
            // printf("==Event");
        if (strncmp(myKey,"Stop",3) == 0)
            mmp->Stop = myresult;
            // printf("==Stop");
    }
    // 结果值都未myresult的最后指向地址的取值，因为这样赋值知识应用
    // printf("end %s",mmp->Name);
    // printf("end %s",mmp->Speed);
    // printf("end %s",mmp->Bit);
    // printf("end %s",mmp->Event);
    // printf("end %s",mmp->Stop);
    fclose(fp);
    return 0;
}


// 需要匹配的字符串，匹配规则
char *reStr(char *test_str, char *reg_str)
{
    int i;
    char ebuff[256];
    int cflags;
    regex_t reg;
    regmatch_t rm[5];
    int ret;
    char *part_str = NULL;
    char result[256];

    cflags = REG_EXTENDED | REG_ICASE;

    ret = regcomp(&reg, reg_str, cflags);
    if (ret)
    {
        regerror(ret, &reg, ebuff, 256);
        fprintf(stderr, "%s\n", ebuff);
        exit(-1);
    }
    ret = regexec(&reg, test_str, 10, rm, 0);
    if (ret)
    {   
        regerror(ret, &reg, ebuff, 256);
        fprintf(stderr, "%s\n", ebuff);
        exit(-1);
    }
    for (i = 0; i < 5; i++)
    {
        if (rm[i].rm_so > -1)
        {
            part_str = strndup(test_str+rm[i].rm_so, rm[i].rm_eo-rm[i].rm_so);
            if (i == 1)
                return part_str;
            free(part_str);
            part_str = NULL;
        }
    }
    exit(-1);
}